package com.block.source.service.receive;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.JuYouHuaParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class JuYouHuaReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        Integer orgId = Integer.valueOf(sourceBaseInfo.getApiKey());

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String body = jsonObjectParamContent.getString("body");

        boolean signBoolean = this.signBoolean(jsonObjectParamContent,body,apiSecret,orgId);
        if (!signBoolean){
            sourceApiResult.setReturnObject(this.getError("撞库签名错误"));
            return sourceApiResult;
        }
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(body);

        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("tid")) || StrUtil.isEmpty(jsonObject.getString("encryptMobile")) || StrUtil.isEmpty(jsonObject.getString("cnName")) || StrUtil.isEmpty(jsonObject.getString("province")) || StrUtil.isEmpty(jsonObject.getString("city")) || jsonObject.getInteger("age") == null || jsonObject.getInteger("sex") == null || jsonObject.getInteger("amount") == null || jsonObject.getInteger("loanTime") == null || jsonObject.getInteger("job") == null || jsonObject.getInteger("salaryPay") == null || jsonObject.getInteger("licenseTime") == null || jsonObject.getInteger("shebao") == null || jsonObject.getInteger("gongjijin") == null || jsonObject.getInteger("house") == null || jsonObject.getInteger("vehicle") == null || jsonObject.getInteger("insurance") == null || jsonObject.getInteger("zhima") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }


//        jsonObject.put("tid",jsonObjectParamContent.getString("tid"));
        String paramContentData1 = JSON.toJSONString(jsonObject);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);

        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.selectEntityByCityNameAndProvinceName(userDataParam.getCity(),userDataParam.getProvince());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        Integer orgId = Integer.valueOf(sourceBaseInfo.getApiKey());

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String body = jsonObjectParamContent.getString("body");

        boolean signBoolean = this.signBoolean(jsonObjectParamContent,body,apiSecret,orgId);
        if (!signBoolean){
            sourceApiResult.setReturnObject(this.getError("撞库签名错误"));
            return sourceApiResult;
        }
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(body);
//        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
//        jsonObject.put("tid",jsonObjectParamContent.getString("tid"));
//        String paramContentData1 = JSON.toJSONString(jsonObject);

        JuYouHuaParam juYouHuaParam = JSON.parseObject(paramContentData, JuYouHuaParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(juYouHuaParam.getMobilePhone());
        userDataParam.setRealName(juYouHuaParam.getCnName());

        String tid = juYouHuaParam.getTid();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), tid);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();

        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "撞库成功！");
        JSONObject dataObject1 = new JSONObject();
        dataObject1.put("status",1);
        dataObject1.put("desc","撞库成功，可进件");

        JSONObject dataObject = new JSONObject();

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){

            dataObject.put("name", thirdBaseInfo.getProductName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }

            dataObject.put("companyName", merchantBaseInfo.getCompanyName());

            if (CollUtil.isEmpty(thirdProtocolInfoList)){
                ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
                ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
                String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());

                dataObject.put("companyAddress", protocolUrl);
            }else{
                dataObject.put("companyAddress", thirdProtocolInfoList.get(0).getProtocolUrl());
            }
        }else{
            dataObject.put("name", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }

            dataObject.put("companyName", merchantBaseInfo.getInfoName());
            //协议地址
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            dataObject.put("companyAddress", protocolUrl);
        }



//        dataObject.put("product_id", pushResultInfo.getOutOrderNo());
        dataObject1.put("extraInfo",dataObject);
        returnObject.put("data", dataObject1);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                returnObject.put("data", null);
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        returnObject.put("data", null);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        returnObject.put("data", null);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        JuYouHuaParam juYouHuaParam = JSON.parseObject(paramContent, JuYouHuaParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setOutOrderNo(juYouHuaParam.getTid());

//        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
//        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        userDataParam.setMobileMd5(juYouHuaParam.getEncryptMobile());
        userDataParam.setMobile(juYouHuaParam.getMobilePhone());
        userDataParam.setRealName(juYouHuaParam.getCnName());
        userDataParam.setSex(String.valueOf(juYouHuaParam.getSex()));
        userDataParam.setAge(juYouHuaParam.getAge());
        userDataParam.setCity(juYouHuaParam.getCity());
        userDataParam.setProvince(juYouHuaParam.getProvince());


        Integer amount = juYouHuaParam.getAmount();
        if (amount == 1) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (amount == 2) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (amount == 3) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        Integer loanTime = juYouHuaParam.getLoanTime();
        if (loanTime == 0){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        }else if (loanTime == 1){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt002.getValue());
        }else if (loanTime == 2){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
        }else {
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt004.getValue());
        }

        Integer job = juYouHuaParam.getJob();
        if (job == 0){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (job == 1){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (job == 3){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }

        Integer shebao = juYouHuaParam.getShebao();
        if (shebao == 0){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        Integer gongjijin = juYouHuaParam.getGongjijin();
        if (gongjijin == 0){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        Integer house = juYouHuaParam.getHouse();
        if (house == 0){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }

        Integer vehicle = juYouHuaParam.getVehicle();
        if (vehicle == 0){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }

        Integer insurance = juYouHuaParam.getInsurance();
        if (insurance == 0){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }

        Integer zhima = juYouHuaParam.getZhima();
        if (zhima == 1){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if (zhima == 2){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }

        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        userDataParam.setUserIp("127.0.0.1");
        userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());

        return userDataParam;
    }

    //验签
    public static boolean signBoolean(JSONObject jsonObject,String body,String apiSecret,Integer orgId){
        Long timestamp = jsonObject.getLong("timestamp");
        String sign = jsonObject.getString("sign");
        String signString = SecureUtil.md5(StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", body, orgId, timestamp, apiSecret)).toLowerCase();
        if (!sign.equals(signString)){
            return false;
        }
        return true;
    }

}
